package cn.bluech.lib.utils;

import android.annotation.SuppressLint;
import android.os.Build;

import java.security.Provider;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Description:
 *   AESUtils.encrypt("12345678","This is data")
 *   AESUtils.decrypt("12345678","AABBCCDDEEFF")
 *   AESUtils.encrypt("12345678","This is data".getBytes())
 *   AESUtils.decrypt("12345678",{0xAA,0xBB,0xCC,0xDD})
 * Create by Codeant on 2018/12/13 0013
 */
public class AESUtils {
    private final static String HEX = "0123456789ABCDEF";

    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];

        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),16).byteValue();

        return result;
    }

    private static String toHex(byte[] buf) {
        if (buf == null)
            return "";

        StringBuffer result = new StringBuffer(2 * buf.length);

        for (byte aBuf : buf) {
            appendHex(result, aBuf);
        }

        return result.toString();
    }


    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

    private static class CryptoProvider extends Provider{
        /**
         * Creates a Provider and puts parameters
         */
        public CryptoProvider() {
            super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
            put("SecureRandom.SHA1PRNG","org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
            put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
        }
    }

    /**
     * 加密
     * @param rawKey 标准格式的密钥(128bit)
     * @param cleartext 明文数据
     * @param iv iv向量
     * @return 密文数据
     */
    public static byte[] encrypt(byte[] rawKey, byte[] cleartext, byte[] iv) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES"); // "DES"
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");         // "DES/CBC/PKCS5PADDING"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
                null!=iv?iv:new byte[cipher.getBlockSize()]));

        return cipher.doFinal(cleartext);

    }

    /**
     * 加密
     * @param rawKey 标准格式的密钥(128bit)
     * @param cleartext 明文数据
     * @return 密文数据
     */
    public static byte[] encrypt(byte[] rawKey, byte[] cleartext) throws Exception {
        return encrypt(rawKey, cleartext, null);
    }

    /**
     * 解密
     * @param rawKey 标准格式的密钥(128bit)
     * @param encrypted 密文数据
     * @param iv iv向量
     * @return 明文数据
     */
    public static byte[] decrypt(byte[] rawKey, byte[] encrypted, byte[] iv)throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES"); // "DES"
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");         // "DES/CBC/PKCS5PADDING"
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(
                null!=iv?iv:new byte[cipher.getBlockSize()]));

        return cipher.doFinal(encrypted);
    }

    /**
     * 解密
     * @param rawKey 标准格式的密钥(128bit)
     * @param encrypted 密文数据
     * @return 明文数据
     */
    public static byte[] decrypt(byte[] rawKey, byte[] encrypted)throws Exception {
        return decrypt(rawKey, encrypted, null);
    }

    /**
     * 通过密钥散列出AES所需的key
     * 新版android密钥生成器已经变化，和java8的生成器已经不同，这里是做兼容java8
     * @param seed 密钥
     * @return 128bit的密钥
     */
    @SuppressLint("TrulyRandom")
    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES"); // "DES"
        SecureRandom sr;
        if(Build.VERSION.SDK_INT >= 28){
            return InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(seed,16);
        }else if(Build.VERSION.SDK_INT >= 17) {
            sr = SecureRandom.getInstance("SHA1PRNG", new CryptoProvider());
        }else {
            sr = SecureRandom.getInstance("SHA1PRNG");
        }
        sr.setSeed(seed);

        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        return skey.getEncoded();
    }

    /**
     * 加密
     * @param pwd 密钥
     * @param cleartext 明文数据
     * @return 加密后的数据(hex形式)
     */
    public static String encrypt(String pwd, String cleartext)throws Exception {
        byte[] rawKey = getRawKey(pwd.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());

        return toHex(result);
    }

    /**
     * 解密
     * @param pwd 密钥
     * @param encrypted 密文(hex形式)
     * @return 解密后的数据
     */
    public static String decrypt(String pwd, String encrypted)throws Exception {
        byte[] rawKey = getRawKey(pwd.getBytes());
        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(rawKey, enc);

        return new String(result);
    }

    /**
     * 加密
     * @param pwd 密钥
     * @param dec 要加密的数据
     * @return 加密后的数据(hex形式)
     */
    public static byte[] encrypt(String pwd, byte[] dec)throws Exception {
        return encrypt(getRawKey(pwd.getBytes()), dec);
    }

    /**
     * 解密
     * @param pwd 密钥
     * @param enc 要解密的数据
     * @return 解密后的数据
     */
    public static byte[] decrypt(String pwd, byte[] enc)throws Exception {
        return decrypt(getRawKey(pwd.getBytes()), enc);
    }
}
